

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 
 * @author pfister
 *
 */
public class CommandClient {
	static String hostname = "127.0.0.1";
	//static String hostname_ = "146.19.4.102";
	public static final int SERVER_PORT = 8260;

	public static void main(String[] args) throws InterruptedException {
		if (args.length > 0)
			hostname = args[0];
		PrintWriter out = null;
		BufferedReader networkIn = null;
		try {
			Socket socket = new Socket(hostname, SERVER_PORT);
			System.out.println("Connected to server");
			networkIn = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			BufferedReader userIn = new BufferedReader(new InputStreamReader(
					System.in));
			out = new PrintWriter(socket.getOutputStream(),true); //autoflush
			while (true) {
				if (socket.isClosed()) {
					System.out.println("server is down");
					break;
				}
				System.out.println(">>"); //prompt
				String userLine = userIn.readLine();
				if (userLine !=null && userLine.equals("."))
					break;
				if (userLine != null) 
				  out.println(userLine);
				String serverResponse = networkIn.readLine();
				if (serverResponse == null) {
					System.out.println("server is down");
					break;
				}
				System.out.println(serverResponse);
			}
		} catch (IOException ex) {
			System.err.println(ex);
		} finally {
			try {
				System.out.println("closing connection - terminated");
				if (networkIn != null)
					networkIn.close();
				if (out != null)
					out.close();
			} catch (IOException ex) {
			}
		}
	}
}
